#include "speechManager.h"

// 构造
SpeechManager::SpeechManager()
{
    this->initSpeech();
    this->createSpeaker();
    this->loadRecord();
}

// 析构
SpeechManager::~SpeechManager()
{

}

// 展示菜单
void SpeechManager::showMenu()
{
    cout << "******************************" << endl;
    cout << "***** 欢迎参数演讲比赛 *****" << endl;
    cout << "***** 1.开始演讲比赛 *****" << endl;
    cout << "***** 2.查看往届记录 *****" << endl;
    cout << "***** 3.清空比赛记录 *****" << endl;
    cout << "***** 0.退出比赛程序 *****" << endl;
    cout << "******************************" << endl;
    cout << endl;
}

// 退出系统
void SpeechManager::exitSystem()
{
    cout << "欢迎下次使用"  << endl;
    system("pause");
    exit(0);
}

// 初始化属性
void SpeechManager::initSpeech()
{
    // 清空所有容器
    this->v1.clear();
    this->v2.clear();
    this->v3.clear();
    this->speaker.clear();

    // 初始化比赛轮数
    this->index = 1;

    // 初始化记录容器
    this->record.clear();
}

// 创建12名选手
void SpeechManager::createSpeaker()
{
    string nameSeed = "ABCDEFGHIJKL";
    for (int i=0; i<12; i++)
    {
        string name = "选手";
        name += nameSeed[i];

        Speaker sp;
        sp.name = name;

        for (int j=0; j<2; j++)
        {
            sp.score[j] = 0;
        }

        // 12个选手编号
        this->v1.push_back(i+10001);

        // 选手编号及对应的选手添加到map中
        this->speaker.insert(make_pair(i+10001, sp));
    }
}

// 比赛
void SpeechManager::startSpeech()
{
    // 第一轮开始比赛
    this->speechDraw();
    this->speechContest();
    this->showScore();
    // 第二轮比赛
    this->index++;
    this->speechDraw();
    this->speechContest();
    this->showScore();
    // 保存分数
    this->saveRecord();

    // 重置比赛
    this->initSpeech();
    this->createSpeaker();
    this->loadRecord();

    cout << "本届比赛完毕" << endl;
    system("pause");
    system("cls");
}

// 抽签
void SpeechManager::speechDraw()
{
    cout << "第" << this->index << "轮比赛选手正在抽签" << endl;
    cout << "------------------------------" << endl;
    cout << "抽签后演讲顺序如下: " << endl;

    if (this->index == 1)
    {
        random_shuffle(v1.begin(), v1.end());
        for (vector<int>::iterator it=v1.begin(); it!=v1.end(); it++)
        {
            cout << *it << " ";
        }
         cout << endl;
    }
    else
    {
        random_shuffle(v2.begin(), v2.end());
        for (vector<int>::iterator it=v2.begin(); it!=v2.end(); it++)
        {
            cout << *it << " ";
        }
         cout << endl;
    }
    cout << "---------------------------------" << endl;
    system("pause");
}

// 比赛
void SpeechManager::speechContest()
{
    cout << "---------第" << this->index << "轮比赛正式开始：--------" << endl;

    // 临时容器，保存分数和编号，从大到小排序
    multimap<double, int, greater<double>>groupScore;

    // 记录人数
    int num = 0;

    vector<int>vSrc;
    if (this->index == 1)
    {
        vSrc = v1;
    }
    else
    {
        vSrc = v2;
    }
    
    // 遍历所有选手
    for (vector<int>::iterator it=vSrc.begin(); it!=vSrc.end(); it++)
    {
        num++;

        // 10个评委打分
        deque<double>d;
        for (int i=0; i<10; i++)
        {
            double score = (rand() % 401 + 600) / 10.f;  // 600~1000
            d.push_back(score);
        }
        sort(d.begin(), d.end(), greater<double>());  // 排序
        d.pop_back();   // 去除最低分
        d.pop_front();  // 去除最高分

        double sum = accumulate(d.begin(), d.end(), 0.0f); // 总分
        double avg = sum / (double)d.size();               // 平均分

        // 保存每个人的平均分
        this->speaker[*it].score[this->index - 1] = avg;

        // 6个人一组，用临时容器保存
        groupScore.insert(make_pair(avg, *it));
        if (num % 6 == 0)
        {
            cout << "第" << num/6 << "小组比赛名次: " << endl;
            for (multimap<double, int, greater<double>>::iterator it=groupScore.begin(); it!=groupScore.end(); it++)
            {
                cout << "编号：" << it->second << "  姓名：" << this->speaker[it->second].name;
                cout << "  成绩：" << this->speaker[it->second].score[this->index - 1] << endl;
            }

            int count = 0;
            // 取前三名
            for (multimap<double, int, greater<double>>::iterator it=groupScore.begin(); it!=groupScore.end() && count < 3; it++, count++)
            {
                if (this->index == 1)
                {
                    v2.push_back((*it).second);
                }
                else
                {
                    v3.push_back((*it).second);
                }
            }
            groupScore.clear();
            cout << endl;
        }
    }
    cout << "---------------第" << this->index << "轮比赛结束--------" << endl;
    system("pause");
}

// 显示比赛成绩
void SpeechManager::showScore()
{
    cout << "-----第" << this->index << "轮晋级选手信息如下------" << endl;
    vector<int> v;
    if (this->index == 1)
    {
        v = v2;
    }
    else
    {
        v = v3;
    }
    
    for (vector<int>::iterator it=v.begin(); it!=v.end(); it++)
    {
        cout << "选手编号：" << *it << " 姓名：" << speaker[*it].name << " 得分";
        cout << speaker[*it].score[this->index - 1] << endl;
    }
    cout << endl;

    system("pause");
    system("cls");
    this->showMenu();
}

// 保存分数
void SpeechManager::saveRecord()
{
    ofstream ofs;
    ofs.open("speech.csv", ios::out | ios::app);

    // 将每个人的数据写入到文件中
    for (vector<int>::iterator it=v3.begin(); it!=v3.end(); it++)
    {
        ofs << *it << "," << speaker[*it].score[1] << ",";
    }
    ofs << endl;

    ofs.close();
    cout << "记录已经保存" << endl;

    this->fileIsEmpty = false;
}

// 读取记录
void SpeechManager::loadRecord()
{
    ifstream ifs("speech.csv", ios::in);
    if(!ifs.is_open())
    {
        this->fileIsEmpty = true;
        cout << "文件不存在" << endl;
        ifs.close();
        return;
    }

    char ch;
    ifs >> ch;
    if(ifs.eof())
    {
        cout << "文件为空" << endl;
        this->fileIsEmpty = true;
        ifs.close();
        return ;
    }

    this->fileIsEmpty = false;
    ifs.putback(ch);  // 读取单个字符

    string data;
    int index = 0;
    while(ifs>>data)
    {
        vector<string> v;

        int pos = -1;
        int start = 0;

        while(true)
        {
            pos = data.find(",", start);
            if (pos == -1)
            {
                break;
            }
            string tmp = data.substr(start, pos-start); // 分割

            v.push_back(tmp);
            start = pos + 1;
        }
        this->record.insert(make_pair(index, v));
        index++;
    }
    ifs.close();
}

// 显示往届记录
void SpeechManager::showRecord()
{
    if (this->fileIsEmpty)
    {
        cout << "文件为空或者不存在" << endl;
    }
    else
    {
        for (int i=0; i<this->record.size(); i++)
        {
            cout << "第" << i+1 << "届";
            cout << "  冠军编号：" << this->record[i][0] << "  得分：" << this->record[i][1];
            cout << "  亚军编号：" << this->record[i][2] << "  得分：" << this->record[i][3];
            cout << "  季军编号：" << this->record[i][4] << "  得分：" << this->record[i][5];
            cout << endl;
        }
    }
    system("pause");
    system("cls");
}

// 清空文件
void SpeechManager::clearRecord()
{
    cout << "确认清空？" << endl;
    cout << "1、确认 \n 2、返回" << endl;

    int select = 0;
    cin >> select;
    if(select == 1){
        ofstream ofs("speech.csv", ios::trunc);
        ofs.close();

        this->initSpeech();
        this->createSpeaker();
        this->loadRecord();

        cout << "清空成功" << endl;
    }
    system("pause");
    system("cls");
}